<template>
	<view>
		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel" ref="framework"
			@AddModuleData_select='AddModuleData_select'>
			<template #content>
				<view class="content" style="width: 100%;height: 100%;">
					<view class="contentBox" style="flex: 1;">
						<view class="container">

							<u--form class="u_form" labelPosition="left" :model="baseFormData" ref="uForm">
								<u-row justify="space-between" gutter="20">

									<u-col span="4">
										<u-form-item labelWidth="auto" label="保养编号:">
											<u--input v-model="baseFormData.BillNO" placeholder="自动带出保养编号" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="保养模具:" @click="openBaseScreen('模具')"
											required>
											<u--input v-model="baseFormData.MoludName" placeholder="请选择保养模具" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="保养人员:" required>
											<u--input v-model="baseFormData.UpkeepMan" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>

								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="保养开始时间:" required>
											<u--input v-model="baseFormData.StartMaintenance" placeholder="自动带出开始时间"
												readonly border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="保养结束时间:" required>
											<u--input v-model="baseFormData.EndMaintenance" placeholder="自动带出结束时间"
												readonly border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="保养周期:" required
											@click="PeriodTypeShow=true">
											<u--input v-model="baseFormData.PeriodTypeName" placeholder="请选择保养周期"
												readonly border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
								</u-row>
							</u--form>
						</view>
						<view class="table">
							<table>
								<tr>
									<th width="10%">序号</th>
									<th>保养项目</th>
									<th width='25%'>保养结果</th>
								</tr>
								<tr v-for="(item, index) in tableData">
									<td>{{index + 1}}</td>
									<td>{{item.UpkeepItemName}}</td>
									<td>
										<uni-data-checkbox v-model="item.FResult" :localdata="sexs" />
									</td>
								</tr>

							</table>

						</view>
					</view>
					<view class=" DetailsbottomBtns" v-show="submitButtonShow">
						<button block @click="submit" class="button1" >
							{{submitButton}}
						</button>
					</view>
				</view>
			</template>
		</st-mc-framework>
		<u-action-sheet :actions="PeriodTypeList" :show="PeriodTypeShow" @select="PeriodTypeClick"
			@close="PeriodTypeShow=false"></u-action-sheet>
		<u-toast ref="uToast"></u-toast>
		<u-datetime-picker :show="Timeshow" v-model="value1" mode="date" @cancel='Timeshow=false'
			@confirm='pickerConfirm'></u-datetime-picker>

		<u-modal :show="modalshow" :title="modaltitle" width="400" @confirm='modalconfirm'>
			<view class="slot-content">
				{{modalcontent}}
			</view>
		</u-modal>
		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
	</view>
</template>

<script>
	import {
		getTimeStamp,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';

	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {
				baseFormData: {
					PeriodTypeName: '日',
					PeriodType: 'D',
					UpkeepMan: '',
					BillDate: '',
					MoludName: '',
					MoludID: ''
				},
				sexs: [{
					text: '合格',
					value: 0
				}, {
					text: '不合格',
					value: 1
				}],
				PeriodTypeShow: false,
				PeriodTypeList: [],
				tableData: [],
				Timeshow: false,
				value1: Number(new Date()),
				submitButton: '',
				submitButtonShow: true,
				modalshow: false,
				modaltitle: '提示',
				modalcontent: '',
				FWorkshopID: null, //模块id
				ModuleTitle: '', //标题
				showMLoading: false,
				loadingName: '正在加载中……',

			};
		},
		onReady() {
			var that = this
			uni.hideLoading();
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			// 初始化状态
			that.GetMJPeriod()

			that.submitButton = '开始保养'
			that.FWorkshopID = MesBasicInfo.FWorkshopID;
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName;
			that.$nextTick(() => {
				setTimeout(() => {
					that.BtnShow = true;
				}, 500)
			})
		},
		onLoad(onLoad) {
			var that = this
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});
			// 缓存状态引用
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = this.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			// 统一处理加载状态
			const setLoading = (state) => this.showMLoading = state;
			// 主处理逻辑
			if (onLoad.UpkeepMouldID) {
				setLoading(true);
				this.queryList(onLoad.UpkeepMouldID);
				return;
			}
			if (onLoad.Detailsitem) {
				setLoading(true);
				const dispatchItem = JSON.parse(onLoad.Detailsitem);
				const formDefaults = {
					...dispatchItem,
					MoludName: dispatchItem.MoludCode
				}
				console.log(formDefaults);
				this.baseFormData = Object.assign(this.baseFormData, formDefaults);
			}
			// 统一处理表单默认值
			const formDefaults = {
				UpkeepMan: UserInfo.EmplName,
				CheckupID: UserInfo.EmplID,
				BillDate: getFormatDateTime(new Date())
			};
			this.assignFormData(this.baseFormData, formDefaults);
			setLoading(false);
			var obj = {
				value: that.baseFormData.PeriodType,
				name: that.baseFormData.PeriodTypeName
			}
			that.PeriodTypeClick(obj)
		},

		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		onShow() {
			var that = this
			uni.$on('refreshDetail', (res) => {
				console.log(res.data);
				this.getValue(res.data); // 调用目标方法
			});
		},
		onUnload() {
			uni.$off('refreshDetail');
		},
		methods: {
			GetMJPeriod() {
				var that = this
				that.Request.request('getPeriod', {
					FType: 'MJBY'
				}, (ret) => {
					ret.data.ds.map(item => {
						item.name = item.PeriodTypeName
						item.value = item.PeriodType
					})
					that.PeriodTypeList = ret.data.ds
				})
			},
			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				var that = this;
				Object.keys(defaults).forEach(key => {
					target[key] = defaults[key];
				});
				that.$forceUpdate();
			},
			replaceFormData(target, source, defaults = {}) {
				Object.keys(defaults).forEach(key => {
					target[key] = source[key] || defaults[key];
				});
				this.$forceUpdate()
			},
			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},
			modalconfirm() {
				var that = this
				that.modalshow = false
			},
			showModal(title, content) {
				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},

			getValue(payload) {
				var that = this;
				const {
					type,
					...data
				} = payload;
				if (payload === '返回') return;
				const typeHandlers = {
					'模具': () => ({
						MoludID: data.MoludID,
						MoludName: data.MoludCode
					})
				};
				if (typeHandlers[type]) {
					Object.assign(this.baseFormData, typeHandlers[type]());
				}
			},
			openBaseScreen(str) {
				var that = this;
				var obj;
				if (str == '模具') {
					obj = {
						cmd: 'ZS_Droplist_Molud',
						type: str,
						serverSearch: {
							isPaging: true, //是否分页
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'searchKey', //搜索关键词，应包含在param中
							showText: 'MoludCode', //查询结果显示的字段
						},
						param: {
							MoludID: 0,
							FWorkshopID: that.FWorkshopID,
							MoludCode: '',
							PageIndex: 1,
							PageSize: 30
						}
					}
				}
				uni.navigateTo({
					url: `../common/baseScreen?obj=${JSON.stringify(obj)}`,
					animationType: 'slide-in-right',
					animationDuration: 300
				});
			},

			pickerConfirm(e) {
				var time = getFormatDateTime(e.value)
				const formDefaults = {
					BillDate: time
				};
				this.assignFormData(this.baseFormData, formDefaults);
				this.Timeshow = false
			},

			PeriodTypeClick(e) {
				var that = this
				const formDefaults = {
					PeriodType: e.value,
					PeriodTypeName: e.name
				};
				that.assignFormData(this.baseFormData, formDefaults);
				that.PeriodTypeShow = false
				that.Request.request('getCheckupItem', {
					PeriodType: e.value,
					FType: 'MJBY'
				}, (ret) => {
					ret.data.ds.map(item => {
						item.FResult = item.FResult ? item.FResult : 0;
						item.UpkeepMouldDeID = item.UpkeepMouldDeID ? item
							.UpkeepMouldDeID : 0
					})
					that.tableData = ret.data.ds
				})
			},

			submit() {
				var that = this

				var msg
				var show = true
				console.log(this.baseFormData);
				if (that.baseFormData.MoludName == '' || that.baseFormData.MoludName == null) {
					msg = '请输入模具'
					show = false
				}
				if (that.tableData.length == 0) {
					msg = '请选择正确的周期'
					show = false
				}
				if (show) {
					var obj = {
						UpkeepMan: that.baseFormData.UpkeepMan,

						UpkeepMouldID: that.baseFormData.UpkeepMouldID ? that.baseFormData
							.UpkeepMouldID : 0,
						PeriodType: that.baseFormData.PeriodType,
						UpID: that.tableData.map(item => item.UpID).join(','),
						UpkeepItemID: that.tableData.map(item => item.UpkeepItemID).join(','),
						FResult: that.tableData.map(item => item.FResult).join(','),
						BillDate: that.baseFormData.BillDate,
						UpkeepItemContent: that.tableData.map(item => item.UpkeepItemContent).join(','),
						UpkeepMouldDeID: that.tableData.map(item => item.UpkeepMouldDeID).join(','),
						FType: 'MJBY',
						MoludID: that.baseFormData.MoludID
					}
					console.log(obj);
					that.Request.request('saveUpkeepMould', obj, function(ret) {
						console.log(ret);
						if (ret.status == 200) {
							that.$refs.uToast.show({
								title: '保存',
								type: 'success',
								message: '保存成功'
							})
							that.queryList(ret.data.ds[0].UpkeepMouldID)
						}
					})
				} else {
					that.showModal('报错', msg);
				}
			},
			queryList(id) {
				var that = this
				try {
					that.Request.request('getUpkeepMouldDetail', {
						UpkeepMouldID: id
					}, (ret) => {
						that.showMLoading = false
						console.log(ret.data);
						const [firstItem] = ret.data.ds;
						const formDefaults = {
							...firstItem,
							StartMaintenance: formatDateTime(firstItem.StartMaintenance),
							EndMaintenance: formatDateTime(firstItem.EndMaintenance),
						};
						that.assignFormData(that.baseFormData, formDefaults)
						that.tableData = ret.data.ds1 || [];
						if (that.baseFormData.BYStatus == 0) {
							that.submitButton = '开始保养'
						} else if (that.baseFormData.BYStatus == 1) {
							that.submitButton = '结束保养'
						} else {
							that.submitButtonShow = false
						}
					}, (err) => {
						that.showMLoading = false
					})
				} catch (e) {
					console.log(e)
					that.showMLoading = false
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},
			changeLevel(list, data, row) {
				getchangeLevel(data)
				uni.$emit('refreshList');
			},
		}
	}
</script>

<style lang="scss" >
	@import "../css/index.css";
</style>